﻿using MaterialDemo.IService.ILogin;
using MaterialDemo.IService.IPermission;
using MaterialDemo.Model.UserDTO;
using MaterialDemo.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MaterialDemo.MVC.Controllers
{
    public class LoginController : Controller
    {
        
            #region  构造函数注入
        private readonly ILogger<LoginController> _logger;
        private readonly ILoggerFactory _loggerFactory;
        private readonly ILogin  _accountService;
        private readonly IRoleService _roleService;
        public LoginController(ILogger<LoginController> logger, ILoggerFactory loggerFactory, ILogin accountService, IRoleService roleService)
        {

            _logger = logger;
            _loggerFactory = loggerFactory;
            _accountService = accountService;
            _roleService = roleService;
        }
        #endregion

        [HttpGet]
        public IActionResult Loginx()
        {
            ////使用方式1
            //_logger.LogError("错误！！！");
            ////使用方式2
            //_loggerFactory.CreateLogger<AccountController>().LogWarning("警告！");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Loginx(string name, string pwd, string verify)
        {

            string verifyCode = base.HttpContext.Session.GetString("CheckCode");
            if (verifyCode == verify && verifyCode.Equals(verify, StringComparison.CurrentCultureIgnoreCase)) // && verifyCode.Equals(verify, StringComparison.CurrentCultureIgnoreCase)
            {
                UserOutput entity = _accountService.Logins(name, pwd);
                if (entity != null)
                {
                    #region session策略

                    HttpContext.Session.SetString("UserId", entity.UserId);
                    HttpContext.Session.SetString("UserName", entity.UserName);

                    //获取角色的权限并存到session

                    string allroleId = _roleService.GetRoleID(entity.UserId);
                    HttpContext.Session.SetString("AllRoleId", allroleId);

                    #endregion

                    #region cookie策略--用户信息---过期时间
                    //var claims = new List<Claim>()
                    //{
                    //    new Claim(ClaimTypes.Name,name),
                    //    new Claim("password",password),//可以写入任意数据
                    //    new Claim("Account","Administrator")
                    //};
                    //var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
                    //HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                    //{
                    //    ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
                    //}).Wait();//没用await
                    #endregion

                    return Redirect("/Home/Index");
                }
                else
                {
                    ViewBag.Msg = "账号密码错误";
                }
            }
            else
            {
                ViewBag.Msg = "验证码错误";
            }
            return View();

        }

        public ActionResult VerifyCode()
        {
            string code = "";
            Bitmap bitmap = VerifyCodeHelper.CreateVerifyCode(out code);
            base.HttpContext.Session.SetString("CheckCode", code);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);
            return File(stream.ToArray(), "image/gif");
        }


        #region 重定向清空session
        public ActionResult Repeat_Login()
        {
            //必须清空session

            HttpContext.Session.Clear();

            return RedirectToAction("Loginx", "Login");

        }
        #endregion
    }
}


